package cn.virens.database.serviceimpl.sys;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.mysql.mapper.sys.SysRoleMapper;
import cn.virens.database.mysql.model.sys.SysRole;
import cn.virens.database.service.sys.SysRoleService;
import cn.virens.exception.APIException;
import cn.virens.util.ztree.Node;
import cn.virens.util.ztree.RootNode;
import cn.virens.util.ztree.cutsom.ResourceNode;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, SysRoleMapper> implements SysRoleService {
	@Autowired
	public SysRoleServiceImpl(SysRoleMapper mBaseMapper) {
		super(mBaseMapper);
	}

	@Override
	public List<Node<String>> getRolePermissions(Integer roleID) {
		List<Map<String, Object>> list = mBaseMapper.getPermissions(roleID);
		RootNode<String> result = new RootNode<>("");
		for (Map<String, Object> map : list) {
			ResourceNode node = new ResourceNode();
			node.setId(MapUtils.getString(map, "code"));
			node.setName(MapUtils.getString(map, "name"));
			node.setPermission(MapUtils.getString(map, "permission"));

			result.addChildren(node);
		}
		return result.getChildren();
	}

	@Override
	@Transactional
	public int saveRolePermission(Integer roleID, Map<String, String> permissions) throws APIException {
		if (roleID == null || roleID == 0) throw new APIException("Null", "角色不存在");
		if (MapUtils.isEmpty(permissions)) throw new APIException("Null", "权限为空");

		int r = mBaseMapper.deletePermissions(roleID);
		int a = mBaseMapper.insertPermissions(roleID, permissions);

		return r | a;
	}

	@Override
	protected Class<SysRole> getGenericSuperclass() {
		return SysRole.class;
	}
}
